/**
 * 字符串计算
 */
#include <stdio.h>
#include <string.h>

void str_appearance_count();
void reverse();

int main() {
    //2.计算字符串出现次数
    str_appearance_count();
    //3.字符串反转
    reverse();


    return 0;
}

/**
 * 查找str中包含dest的位置 https://www.bilibili.com/video/BV1vs411n7TH/?p=78
 * @param src 原字符串
 * @param dest 查找的字符串
 * @return 如果没找到, 返回NULL
 */
char* str_str(char* src, char dest[]) {
    char* fsrc = src;     //用于循环遍历的指针
    char* rsrc;           //记录每次相同的首地址
    char* tdest = dest;
    while (*fsrc) {
        rsrc = fsrc;
        //FIXME 2023年1月22日19:27 感觉下方的判断不正确?
        while (*fsrc == *tdest && *fsrc != 0) {
            fsrc++;
            tdest++;
        }
        if (*tdest == 0) {
            return rsrc;
        }
        //回滚
        fsrc = rsrc;
        tdest = dest;
        fsrc++;
    }
    return NULL;
}

/**
 * 2.计算字符串出现次数 https://www.bilibili.com/video/BV1vs411n7TH/?p=79
 */
void str_appearance_count() {
    char* str = "11abcd111122abcd333abcd3322abcd3333322qqq";
    char ch[] = "abcd";
    short count = 0;
    char *result = str;
    while (result = str_str(result, ch)) {
        count++;
        printf("在str中第 %d 次查找到'%s': %s\n", count, ch, result);
        result++;
    }
}

/**
 * 3.字符串反转 https://www.bilibili.com/video/BV1vs411n7TH?p=81
 */
void reverse() {
    char arr[] = "Hello World!";
    if (arr == NULL) return;
    size_t len = strlen(arr);
    char temp;
    //1.用数组交换
//    int i = 0, j = len - 1;
//    while(i < j) {
//        temp = arr[i];
//        arr[i] = arr[j];
//        arr[j] = temp;
//        i++;
//        j--;
//    }

    //2.用指针
    char *start = arr, *end = arr + len - 1;
    while (start < end) {       //指针相减
        temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
    printf("反转后: %s\n", arr);


    char* str0 = "Hello撒地方";
    char* str1 = "Hello撒地方";
    char arr0[100] = "hello world";
    char arr1[100] = "hello";
    char arr2[]    = "hello\0abc";
    char arr3[]    = "hello\0abc";
    char arr4[]    = "hello\0def";
    int re1 = str0 == str1;         //1: 可以, 因为这2个字符串都是常量
    int re2 = arr0 == arr1;         //0: 数组 不可以通过==来比较

    /**
     * int strcmp(const char * _Str1, const char * _Str2);
     * 返回值:
     *  =0: 相等
     *  >0: 不同操作系统返回的结果不同, 有的返回差值, 有的返回±1
     *  <0:
     */
    int re3 = strcmp(arr0, arr1);   //1
    int re4 = strcmp(arr2, arr3);   //0
    int re5 = strcmp(arr3, arr4);   //0

    //只比较前5个字符
    int re6 = strncmp(arr0, arr1, 5);//0
    printf("re1 = %d, re2 = %d, re3 = %d, re4 = %d, re5 = %d, re6 = %d\n", re1, re2, re3, re4, re5, re6);
}
